<?php
use \phiction\exceptions\internal_error;
use \phiction\link;
use \phiction\config;
use \phiction\html;
use \phiction\schema_loader;
use \phiction\query_builder;
use \phiction\mapper;

try{
    $html = null;
    try {
        require_once 'phiction/loader.php';

        set_error_handler(function ($code, $msg) {
            throw new internal_error($msg, $code);
        }, E_ALL);

        $config = config::detected();
        $html = new html($config);
        if (link::is_static($config->request))
            return false;

        $ld = new schema_loader;
        $ld->scan();

        $pdo = database::get()->connect();
        $q = new query_builder($ld, $pdo);

        $mapper = new mapper($config, $q, $html);
        $result = $mapper->map($config->request);
        $type = $result['type'];
        $result = $result['result'];
    }
    catch (\Throwable $ex) {
        if (is_null($html)) throw $ex;
        error_log($ex);
        $result = mapper::render_bad_page($ex->getMessage(), $html);
        $type = $result['type'];
        $result = $result['result'];
    }
}
catch (\Throwable $ex) {
    error_log($ex);
    $type = 'text/plain';
    $result = $ex->getMessage();
}

header("Content-Type: $type; charset=utf-8");
echo $result;
//var_export($_SERVER);

